package leetcode.median;

import java.util.ArrayDeque;
import java.util.Deque;

public class $71_SimplifyPath {
    public String simplifyPath(String path) {
        String[] dirs = path.split("/");
        Deque<String> stack = new ArrayDeque<>();
        for (String dir : dirs) {
            if ("..".equals(dir)) {
                if (!stack.isEmpty()) {
                    stack.pollFirst();
                }
            } else if (dir.length() > 0 && !".".equals(dir)){
                stack.push(dir);
            }
        }
        StringBuilder sb = new StringBuilder();
        if (stack.isEmpty()) {
            sb.append('/');
        } else {
            while (!stack.isEmpty()) {
                sb.append('/');
                sb.append(stack.pollLast());
            }
        }
        return sb.toString();
    }
}
